/*
 * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU.
 * Copyright (c) 2006-2018 Christian Walter <cwalter@embedded-solutions.at>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * File: $Id: mbutils.c,v 1.6 2007/02/18 23:49:07 wolti Exp $
 */

/* ----------------------- System includes ----------------------------------*/
#include "stdlib.h"
#include "string.h"

/* ----------------------- Platform includes --------------------------------*/
#include "port.h"

/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbproto.h"

/* ----------------------- Defines ------------------------------------------*/
#define BITS_UCHAR 8U

/* ----------------------- Start implementation -----------------------------*/

/**
 * Modbus master coils callback function.   有点不好理解
 *
 * @param ucByteBuf 指向待写入的字节
 * @param usBitOffset 指示要写入的线圈数据在上面的字节中的位置(0~7)
 * @param usNCoils 要写入的线圈数量
 * @param ucValue 含有线圈数据的字节
 * @return 无
 */
void xMBUtilSetBits(UCHAR* ucByteBuf, USHORT usBitOffset, UCHAR ucNBits, UCHAR ucValue)
{ // 这里的ucValue是数据源  usBitOffset的取值范围在0-7  是在一个字节中的偏移量
    USHORT usWordBuf;
    USHORT usMask;
    USHORT usByteOffset;
    USHORT usNPreBits;
    USHORT usValue = ucValue;

    assert_param(ucNBits <= 8); // 这里必须小于等于8才行
    assert_param((size_t)BITS_UCHAR == sizeof(UCHAR) * 8); // 这里一定可以成立

    /* Calculate byte offset for first byte containing the bit values starting
     * at usBitOffset. */
    usByteOffset = (USHORT)((usBitOffset) / BITS_UCHAR); // 这里是字节偏移 0(一定是)

    /* How many bits precede our bits to set. */
    usNPreBits = (USHORT)(usBitOffset - usByteOffset * BITS_UCHAR); // 这里是bit偏移  usBitOffset==usNPreBits

    /* Move bit field into position over bits to set */
    usValue <<= usNPreBits; // 相当于   ucValue = ucValue << usBitOffset   //就是将 0b00000001变成  0b00001000

    /* Prepare a mask for setting the new bits. */
    usMask = (USHORT)((1 << (USHORT)ucNBits) - 1); // 这里变成了8个1 即0x00FF  即 ucNBits个1
    usMask <<= usBitOffset - usByteOffset * BITS_UCHAR; // 这里相当于  usMask=usMask<< usBitOffset

    /* copy bits into temporary storage. */
    usWordBuf = ucByteBuf[usByteOffset]; // 这里是低8字节
    usWordBuf |= ucByteBuf[usByteOffset + 1] << BITS_UCHAR; //  ucByteBuf[usByteOffset + 1] << BITS_UCHAR这里是高8字节
    // 上面相当于  (ucByteBuf[usByteOffset + 1]<<8)|(ucByteBuf[usByteOffset])
    /* Zero out bit field bits and then or value bits into them. */
    usWordBuf = (USHORT)((usWordBuf & (~usMask)) | usValue); // 这里是将usBitOffset开始的bit清零,并置为usValue值
    // 这里的usValue也是被左移了usBitOffset比特的
    /* move bits back into storage */
    ucByteBuf[usByteOffset] = (UCHAR)(usWordBuf & 0xFF);
    ucByteBuf[usByteOffset + 1] = (UCHAR)(usWordBuf >> BITS_UCHAR);
} // 这个函数的核心就是将  usValue贴在usWordBuf中usBitOffset的偏移位置

UCHAR
xMBUtilGetBits(UCHAR* ucByteBuf, USHORT usBitOffset, UCHAR ucNBits)
{
    USHORT usWordBuf;
    USHORT usMask;
    USHORT usByteOffset;
    USHORT usNPreBits;

    /* Calculate byte offset for first byte containing the bit values starting
     * at usBitOffset. */
    usByteOffset = (USHORT)((usBitOffset) / BITS_UCHAR); // 传进来时值小于8,除以8当然等于0

    /* How many bits precede our bits to set. */
    usNPreBits = (USHORT)(usBitOffset - usByteOffset * BITS_UCHAR); // 用一个字节表示1bit??

    /* Prepare a mask for setting the new bits. */
    usMask = (USHORT)((1 << (USHORT)ucNBits) - 1); // usMask现在变为了0x00FF  相当于变出ucNBits个bit 1

    /* copy bits into temporary storage. */
    usWordBuf = ucByteBuf[usByteOffset]; // 字节的低8位
    usWordBuf |= ucByteBuf[usByteOffset + 1] << BITS_UCHAR; // ucByteBuf[usByteOffset + 1] << BITS_UCHAR 字节的高8位

    /* throw away unneeded bits. */
    usWordBuf >>= usNPreBits; // usWordBuf= usWordBuf >> usNPreBits  这里算是将开始地址前面的几位给抹了

    /* mask away bits above the requested bitfield. */
    usWordBuf &= usMask; // 只取8bit

    return (UCHAR)usWordBuf; // 返回以usBitOffset为开始bit的一个字节
}

eMBException prveMBError2Exception(eMBErrorCode eErrorCode)
{ // 将modbus的错误码转换为modbus的标准错误
    // typedef enum {
    //     MB_ENOERR, /*!< no error. */
    //     MB_ENOREG, /*!< illegal register address. */
    //     MB_EINVAL, /*!< illegal argument. */
    //     MB_EPORTERR, /*!< porting layer error. */
    //     MB_ENORES, /*!< insufficient resources. */
    //     MB_EIO, /*!< I/O error. */
    //     MB_EILLSTATE, /*!< protocol stack in illegal state. */
    //     MB_ETIMEDOUT /*!< timeout error occurred. */
    // } eMBErrorCode; //这里是modbus错误码!

    // typedef enum {
    //     MB_EX_NONE = 0x00,
    //     MB_EX_ILLEGAL_FUNCTION = 0x01,
    //     MB_EX_ILLEGAL_DATA_ADDRESS = 0x02,
    //     MB_EX_ILLEGAL_DATA_VALUE = 0x03,
    //     MB_EX_SLAVE_DEVICE_FAILURE = 0x04,
    //     MB_EX_ACKNOWLEDGE = 0x05,
    //     MB_EX_SLAVE_BUSY = 0x06,
    //     MB_EX_MEMORY_PARITY_ERROR = 0x08,
    //     MB_EX_GATEWAY_PATH_FAILED = 0x0A,
    //     MB_EX_GATEWAY_TGT_FAILED = 0x0B
    // } eMBException; //这里是modbus异常!

    eMBException eStatus;

    switch (eErrorCode) {
    case MB_ENOERR:
        eStatus = MB_EX_NONE;
        break;

    case MB_ENOREG: // 非法的寄存器地址
        eStatus = MB_EX_ILLEGAL_DATA_ADDRESS; // 非法的数据地址
        break;

    case MB_ETIMEDOUT: // 超时错误
        eStatus = MB_EX_SLAVE_BUSY; // 从机超时
        break;

    default:
        eStatus = MB_EX_SLAVE_DEVICE_FAILURE;
        break;
    }

    return eStatus;
}
